package com.bootcamp.javase.basic1;

/**
 * @program: BlockCode
 * @description: contains tools manipulating array list；对每个提示 黄色 地方 Alt+Enter
 * @author: Keyu Li
 * @create: 2021-08-30 20:14
 **/

public class ArrayTool {
    public static void main(String[] args) {
        int[] arr = {12, 6, 23, 324, 343, 232, 90, 9, 2, 65, 6};
        iterateArray(arr);
        System.out.println("max value is " + getMaxValue(arr));
        System.out.println("min value is " + getMinValue(arr));
        reverseArray(arr);
        iterateArray(arr);
        System.out.println("index of the first 5 is " + findFirstIndex(arr, 5));
        System.out.println("index of the last 5 is " + findLastIndex(arr, 5));
        System.out.println("index of the first 6 is " + findFirstIndex(arr, 6));
        System.out.println("index of the last 6 is " + findLastIndex(arr, 6));
    }

    private static boolean isEmptyOrNull(int[] arr) {
        if (arr == null) {
            System.out.println("null");
            return true;
        }
        if (arr.length == 0) {
            System.out.println("[]");
            return true;
        }
        return false;
    }

    private static void iterateArray(int[] arr) {
        if (isEmptyOrNull(arr))
            return;
        System.out.print("[");
        for (int i1 : arr) {
            System.out.print(i1 + ",");
        }
        System.out.println("\b]");
    }

    private static Integer getMaxValue(int[] arr) {
        if (isEmptyOrNull(arr))
            return null;
        int max = arr[0];
        for (int i1 : arr) {
            max = max < i1 ? i1 : max;
        }
        return max;
    }

    private static Integer getMinValue(int[] arr) {
        if (isEmptyOrNull(arr))
            return null;
        int min = arr[0];
        for (int i = 0; i < arr.length; i++) {
            min = min > arr[i] ? arr[i] : min;
        }
        return min;
    }

    private static void reverseArray(int[] arr) {
        if (isEmptyOrNull(arr))
            return;
        int temp;
        for (int i = 0; i < arr.length / 2; i++) {
            temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
    }

    private static int findFirstIndex(int[] arr, int target) {
        if (isEmptyOrNull(arr))
            return -1;
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] == target)
                return i;
        }
        return -1;
    }

    private static int findLastIndex(int[] arr, int target) {
        if (isEmptyOrNull(arr))
            return -1;
        for (int i = arr.length - 1; i >= 0; i--) {
            if (arr[i] == target)
                return i;
        }
        return -1;
    }
}
